package com.mrart.session.dao;

import java.io.Serializable;

import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.ValidatingSession;
import org.apache.shiro.session.mgt.eis.CachingSessionDAO;
import org.springframework.beans.factory.annotation.Autowired;

import com.mrart.session.entity.Sessions;
import com.mrart.session.mapper.SessionsMapper;
import com.mrart.utils.SerializableUtils;

public class MySqlSessionDAO extends CachingSessionDAO {
    
    @Autowired
    private SessionsMapper sessionsMapper;

    @Override
    protected void doDelete(Session session) {
        sessionsMapper.deleteByPrimaryKey(session.getId().toString());
    }

    @Override
    protected void doUpdate(Session session) {
        if(session instanceof ValidatingSession && !((ValidatingSession)session).isValid()) {
            return; //如果会话过期/停止 没必要再更新了
        }
        Sessions updateSession = new Sessions(session.getId().toString(), 
                SerializableUtils.serialize(session));
        sessionsMapper.updateByPrimaryKeySelective(updateSession);
    }

    @Override
    protected Serializable doCreate(Session session) {
        Serializable sessionId = generateSessionId(session);
        assignSessionId(session, sessionId);
        Sessions sessions = new Sessions(sessionId.toString(), SerializableUtils.serialize(session));
        sessionsMapper.insertSelective(sessions);
        return session.getId();
    }

    @Override
    protected Session doReadSession(Serializable sessionId) {
        String sessionStr = sessionsMapper.selectSessionByPrimaryKey(sessionId.toString());
        if(sessionStr == null) {
            return null;
        }
        return SerializableUtils.deserialize(sessionStr);
    }

}
